package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(401);
            return false;
        }

        User user = findByToken(token);
        if (user == null) {
            response.setStatus(401);
            return false;
        }

        UserHolder.setUser(user);
        return true;
    }

    private User findByToken(String token){
        //从redis中查找缓存的用户User
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (userJson != null) {
            //找到用户后，给redis缓存的用户延长生存时间
            redisTemplate.opsForValue().set("TOKEN_" + token, userJson, Duration.ofHours(1));
            return JSON.parseObject(userJson, User.class);
        }
        return null;
    }
}
